#
# SPLIT FILE ON FIELD IDENTIFIER or SQL Query
# Compatible with ArcGIS 10 and Python 2.6.x
#
# Created on: 7/22/2012
#    Author: Kyle Taylor (kyle.a.taylor@gmail.com)
#    Written for Idaho Fish and Game, 2012
#
# Searches an input shape file for a field value you specify, such as
# "Ear_Tag", and then dumps all of the unique values of that field value
# into individual shape files.  Additionally, you can generate GME scripts and
# specify SQL statements to run along with the field value tag to further subdivide
# data.  This is meant to fix the shortcomings of the point-data-splitter application.
# 
# Usage:   split-file-on-field <input shapefile path> <field deliminator> [option]
#
# Option:  --sql STATEMENT 
#          Will tag STATEMENT on after the initial field deliminator.  This is useful for parsing things like date ranges.  
#          --generate-gme-script
#          Will generate a GME script for appropriate data and then attempt to run that script automatically.
#
# Example: split-file-on-field "C:\Users\ktaylor\Desktop\2007\2007.shp" "Ear_Tag" --sql "DATE >= 1/1/2007 AND DATE < 2/3/2007"
#

import sys, os

# Options
USING_ADD_SQL_OPTION = "N"
USING_GENERATE_GME_OPTION = "N"

# Parameters
SQL_Statment = "NULL"

# Parse user runtime input

if len(sys.argv) < 3:
  print " "
  print sys.argv[0] + " takes atleast 2 arguments: " + sys.argv[0] + " <shapefile> <field deliminator> [options]\n"
  print "Options: "
  print "--generate-gme-script"
  print "--sql STATEMENT"
  sys.exit()
  
# Iterate through additional arguments to find out what they are and act accordingly
elif len(sys.argv) > 3:
  for n in range(len(sys.argv)):
    if str(sys.argv[n]) == "--sql":
      USING_ADD_SQL_OPTION = "Y"
      SQL_Statement = str(sys.argv[n+1])
    elif str(sys.argv[n]) == "--generate-gme-script":
      USING_GENERATE_GME_OPTION = "Y"
else:
    USING_ADD_SQL_OPTION = "N"

print "\n#### Split File on Field ####"
print " ... attempting to load ArcGIS 10 and Spatial Analysis Extensions..."

try:
  import arcpy
  # if not arcpy.CheckOutExtension("spatial"):
  #  print "failed to load extensions and framework.  quitting.\n"
  #  sys.exit()
except ImportError:
  print "\nfailed to load arcpy module.  Are you using a workstation with ArcGIS 10 installed?\n"

## Create Necessary Files in our Workspace

print " ... checking workspace file structures."

script_path = os.path.abspath(__file__) # Not crossplatform, but that doesn't matter.  The only client that can run the GP is Win 6.x + anyway.
script_path = script_path[:script_path.rfind('\\')]

if not os.path.exists(script_path + '\\' + "split data"):
    os.mkdir(script_path + '\\' + "split data")
if not os.path.exists(script_path + "\\split data\\" + "Point Data"):
    os.mkdir(script_path + "\\split data\\" + "Point Data")
if USING_GENERATE_GME_OPTION == "Y":    
  BatchScript = open(script_path + "\\split data\\" + "gme_batch_script.txt","w")

## Go

input_shp = sys.argv[1]
field_delim = sys.argv[2]

# prime the pump 

rows = arcpy.SearchCursor(input_shp)
row = rows.next()

unique_fields = []

while row:
  try:

    value = row.getValue(field_delim)

    if(value%1 != 0): # check for a floating point
      value = "%.2f" % round(value,2) # if we are dealing with floating point nums, round to two places.
      value = str(value)
    else:  # using whole number or string
      value = str(value)[:-2]
    
      if value not in unique_fields:
        unique_fields.append(value)
	  
    row = rows.next()
  except AttributeError:
    print "... caught an Attribute Error while trying to parse field "+ field_delim + ".  Does the input shapefile contain that field?"
    print "    check your spelling and syntax and try again.\n"
    sys.exit()

unique_fields.sort()
print " ... found", len(unique_fields), "unique fields to split."

shapes = []

for i in range(len(unique_fields)):

  shapes.append(script_path + "\\split data\\Point Data\\" + str(unique_fields[i]))
  
  if USING_ADD_SQL_OPTION == "Y":
    parseThis = field_delim + " = " + str(unique_fields[i]) + " AND " + SQL_Statement
  else:
    parseThis = field_delim + " = " + str(unique_fields[i])
	
  print "     creating shapefile for : " +  parseThis
  arcpy.Select_analysis(input_shp, shapes[i] + ".shp",  parseThis)

  if USING_GENERATE_GME_OPTION == "Y":
    # Write a KDE entry to our GME batch script            
    BatchScript.write("kde(in=" + '\"' + shapes[i] + ".shp" + '\"' + \
                      ", out=" + '\"' + shapes[i] + ".tif" + '\"' + \
                      ", bandwidth=0.0000045, cellsize=0.00045);\n")
    # Write an isopleth() entry to our GME batch script
    BatchScript.write("isopleth(in=" + '\"' + shapes[i] + ".tif" + '\"' + \
                      ", out=" + '\"' + script_path + "\\split data\\P95 Interval\\" + \
                      str(unique_fields[i]) + ".p95.shp" + '\"' + \
                      ", quantiles=\"0.95\");\n")

if USING_GENERATE_GME_OPTION == "Y":
    print " ... launching GME to run generated script."
    BatchScript.close()
    os.system("C:\\PROGRA~1\\SpatialEcology\\GME\\SEGME.exe" + " run(in=" + "'\"'" + script_path + "\\split data\\" + "gme_batch_script.txt" + "'\"'" + ");")

sys.exit()
